/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.common;

import com.inspur.edp.lcm.metadata.common.ServiceUtils;
import com.inspur.edp.lcm.metadata.common.configuration.MetadataServiceHelper;
import com.inspur.edp.metadata.rtcustomization.api.entity.config.CustomizationConfiguration;
import java.util.List;

import com.inspur.edp.metadata.rtcustomization.api.exception.LcmConfigResolveException;
import com.inspur.edp.metadata.rtcustomization.api.exception.ErrorCodes;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


/**
 * @author zhaoleitr
 */
public class CustomizationConfigLoader {
    public static String fileName = "config/platform/common/lcm_rtcustomization.json";
    private static String sectionName = "CustomizationConfiguration";
    private String absoluteFilePath;
    public String getAbsoluteFilePath() {
        if (StringUtils.isEmpty(absoluteFilePath)) {
            absoluteFilePath = ServiceUtils.getAbsoluteConfigFilePath(fileName);
        }
        return absoluteFilePath;
    }

    private List<CustomizationConfiguration> customizationConfigurations;

    public CustomizationConfigLoader() {
        loadCustomizationConfigurations();
    }

    protected List<CustomizationConfiguration> loadCustomizationConfigurations() {
        try {
            if (CollectionUtils.isEmpty(customizationConfigurations)) {
                customizationConfigurations = MetadataServiceHelper.getConfigurationList(getAbsoluteFilePath(), sectionName, CustomizationConfiguration.class);
            }
            return customizationConfigurations;
        } catch (Exception e) {
            throw new LcmConfigResolveException(e, ErrorCodes.ECP_CONFIG_RESOLVE_0002, absoluteFilePath);
        }
    }

    protected CustomizationConfiguration getCustomizationConfigurationData(String typeName){
        loadCustomizationConfigurations();
        if (customizationConfigurations != null && customizationConfigurations.size()>0){
            for (CustomizationConfiguration data : customizationConfigurations){
                if (data.getCommon().getTypeCode().equalsIgnoreCase(typeName) ){
                    return data;
                }
            }
        }else {
            return null;
        }
        return null;
    }
}
